import axios from 'axios'
import { Homework, HomeworkSubmission, HomeworkFilter, HomeworkStatistics } from '../types/homework'

export const homeworkService = {
  async getHomeworksByCourse(courseId: string, filter?: HomeworkFilter) {
    try {
      const response = await axios.get(`/api/courses/${courseId}/homeworks`, { params: filter })
      return response.data as Homework[]
    } catch (error) {
      throw new Error('获取作业列表失败')
    }
  },

  async getHomeworkDetail(homeworkId: string) {
    try {
      const response = await axios.get(`/api/homeworks/${homeworkId}`)
      return response.data as Homework
    } catch (error) {
      throw new Error('获取作业详情失败')
    }
  },

  async submitHomework(homeworkId: string, submission: FormData) {
    try {
      const response = await axios.post(`/api/homeworks/${homeworkId}/submit`, submission, {
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      return response.data as HomeworkSubmission
    } catch (error) {
      throw new Error('提交作业失败')
    }
  },

  async getStudentSubmissions(courseId: string, studentId: string) {
    try {
      const response = await axios.get(`/api/courses/${courseId}/submissions/${studentId}`)
      return response.data as HomeworkSubmission[]
    } catch (error) {
      throw new Error('获取学生作业提交列表失败')
    }
  },

  async gradeHomework(submissionId: string, gradeData: { grade: number; feedback?: string }) {
    try {
      const response = await axios.post(`/api/submissions/${submissionId}/grade`, gradeData)
      return response.data as HomeworkSubmission
    } catch (error) {
      throw new Error('批改作业失败')
    }
  },

  async getHomeworkStatistics(courseId: string) {
    try {
      const response = await axios.get(`/api/courses/${courseId}/homework-stats`)
      return response.data as HomeworkStatistics
    } catch (error) {
      throw new Error('获取作业统计失败')
    }
  }
}
